<template>
  <div class="bookkeeping">
    <header-go-back text="编辑" @ok="handleGoEditClass" @back="handleGoBack" center>
      <template v-slot:title>
        <div class="header_type">
          <div :class="{'header_select_type': selectedType === 'pay', 'header_type_item': true}" @click="handleSelectedType('pay')">支出</div>|
          <div :class="{'header_select_type': selectedType === 'income', 'header_type_item': true}" @click="handleSelectedType('income')">收入</div>
          <!-- <div :class="{'header_select_type': selectedType === 'turn', 'header_type_item': true}" @click="handleSelectedType('turn')">转账</div> -->
        </div>
      </template>
    </header-go-back>
    <bookkeeping-grid 
      :data="data" 
      :type="selectedType" 
      @type="getSelectedType"
      ref="bookGrid"
    ></bookkeeping-grid>
    <div class="bookkeeping_input">
      <div class="input_show">
        <div class="input_label"><i class="iconfont icon-biaoqian"></i>备注</div>
        <input type="text" placeholder="添加备注" v-model="formData.desc">
        <div class="input_money">{{ money }}</div>
      </div>
      <div class="input_info">
        <div class="input_date" @click.stop="dateVisible = true"><i class="iconfont icon-icon"></i>{{ date === today ? '今天' : date }}</div>
        <div class="input_book" @click="bookVisible = true"><i :class=" ['iconfont', book.icon]"></i>{{ book? book.name:"暂未选择"}}</div>
      </div>
      <div class="input_number">
        <div 
          :class="{
            'input_cancel_item': item === '取消',
            'input_finish_item': (cancelValue !== '取消' && item === '取消') || (cancelValue === '完成' && item === '再记')}" 
          class="input_number_item" 
          v-for="(item, index) in inputData" 
          :key="'input'+index" 
          @click="handleClickNumber(item)"
        >
          <i v-if="item === '←'" class="iconfont icon-shanchu"></i>
          {{ item === '←' ? '' : (item === '取消' ? cancelValue : item) }}</div>
      </div>
    </div>
    <van-calendar
      color="#ff7c79" 
      position="right"
      :round="false"
      v-model:show="dateVisible" 
      :min-date="showData.start"
      :max-date="showData.end"
      @confirm="onDateConfirm" 
      :default-date="defaultDate"
    />
    <van-action-sheet 
      v-model:show="bookVisible" 
      :closeable="false"
    >
      <div class="click_book">
        <div class="click_book_header">
          <div class="header_title">选择账本</div>
          <div class="header_button" @click="handleGoBook"><i class="iconfont icon-benzi"></i> 账本管理</div>
        </div>
        <div class="click_book_body" v-for="(item, index) in bookData" :key="'book' + index">
          <div class="click_book_item" @click="handleClickBook(item)">
            <i :class="['iconfont', item.icon]"></i>
            <p>{{ item.name }}</p>
          </div>
        </div>
      </div>
    </van-action-sheet>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import dayjs from 'dayjs'
import BookkeepingGrid from '@/components/bill/BookkeepingGrid.vue'
import { createBill, getBillDetail, updateBill } from '@/api/bill'
import { useStore } from 'vuex'
import HeaderGoBack from '@/components/common/HeaderGoBack.vue'
import { getStartAndEnd, setCalendarShowData } from '@/utils/helper'
export default defineComponent({
    components: {
    BookkeepingGrid,
    HeaderGoBack
  },
  setup() {
    const router = useRouter()
    const route = useRoute()
    const store = useStore()
    const date = ref([])
    const today = dayjs().format('M月D日') as never
    const defaultDate = ref(new Date())
    const showData = reactive({
      start: new Date(),
      end: new Date()
    })
    const showMonth = ref(3)
    const selectedType = ref("pay")
    const formData = ref({
      type: '',
      titleId: '',
      icon: '',
      money: 0,
      date: '',
      bookId: '',
      desc: ''
    })
    const data = ref([])
    const money = ref('0')
    const cancelValue = ref('取消')
    const editClassVisible = ref(false)
    const dateVisible = ref(false)
    const bookVisible = ref(false)
    const bookGrid = ref()
    const inputData = [
      '1', '2', '3', '←', '4', '5', '6', '-', '7', '8', '9', '+', '再记', '0', '.', '取消'
    ]
    const payData = computed(() => store.state.payClassList)
    const incomeData = computed(() => store.state.incomeClassList)
    const bookData = computed(() => store.state.bookList)
    const book = computed(() => store.state.book)
    const bookkeepingType = computed(() => route.query.type)
    const bookkeepingId = ref(-1)
    data.value = payData.value || [{children: []}]
    // 获取日历展示的日期区间
    const setShowData = () => {
      const { start, end } = setCalendarShowData(showMonth.value)
      showData.start = start
      showData.end = end
    }
    setShowData()
    // 选择记账的类型为：收入 / 支出 / 转账
    const handleSelectedType = (type: string) => {
        selectedType.value = type;
        switch (type) {
          case 'pay':
            data.value = payData.value
            break;
          case 'income':
            data.value = incomeData.value
            break;
          case 'turn':
            data.value = []
            break;
          default:
            break;
        }
    };
    // 计算money的值
    const calculationFunc = (money: string) => {
      return eval(money).toFixed(2)
    }
    // 记账完成 / 再记时触发的函数
    const handleFinish = async () => {
      calculationFunc(money.value + '+0')
      formData.value.money = Number(money.value)
      formData.value.type = selectedType.value
      formData.value.bookId = book.value.id
      if(bookkeepingType.value === 'edit') {
        await updateBill({
          ...formData.value,
          id: bookkeepingId.value
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        }).then((res:any) => {
          if(res.code === 100) {
            alert('修改成功')
            getBillList()
          }
        })
      } else {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        await createBill(formData.value).then((res:any) => {
          if(res.code === 100) {
            alert('新建成功')
            getBillList()
          }
        })
      }
      money.value = '0'
    }
    // 获取首页账本数据
    const getBillList = () => {
      const date = getStartAndEnd(new Date())
      const start = dayjs(date.start).format('YYYY-MM-DD 00:00:00')
      const end = dayjs(date.end).format('YYYY-MM-DD 23:59:59')
      store.dispatch('fetchBillList', {
        end: end,
        start: start,
        type: 'day',
        bookIds: book.value.id
      })
      store.dispatch('fetchBillTotal', {
        end: end,
        start: start,
        type: 'month',
        bookIds: book.value.id
      })
    }
    // 点击键盘触发
    const handleClickNumber = (number: string) => {
      switch (number) {
        case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '0': case '.':
          if(money.value === '0') {
            money.value = number
          } else {
            money.value = money.value + number
          }
          break;
        case '+': case '-': 
          if(money.value.indexOf('+') >-1 || money.value.indexOf('-') >-1) {
            money.value = calculationFunc(money.value)
          }
          money.value = money.value + number
          cancelValue.value = '='
          break;
        case '←':
          money.value = money.value.substring(0, money.value.length - 1);
          if(money.value.length === 0) {
            cancelValue.value = '取消'
          }
          break;
        case '取消':
          // 取消，完成，=
          if(cancelValue.value === '=') {
            money.value = calculationFunc(money.value)
          } else if(cancelValue.value === '取消') {
            handleGoBack()
          } else if(cancelValue.value === '完成') {
            handleFinish()
            handleGoBack()
          }
          break;
        case '再记':
          if(cancelValue.value === '完成') {
            handleFinish()
            cancelValue.value = '取消'
          }
          break;
        default:
          break;
      }
      if(money.value === '') {
        money.value = '0'
      }
      if(!money.value.includes('+') && !money.value.includes('-') && money.value !== '0') {
        cancelValue.value = '完成'
      }
      
    }
    // 回到首页
    const handleGoBack = () => {
      if(bookkeepingType.value === 'edit') {
        router.push({
          path: '/billDetail',
          query: {
            id: bookkeepingId.value
          }
        })
      } else {
        router.back()
      }
    }
    // 获取记账宫格传递回来的值：选中的记账大类-小类
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const getSelectedType = (data: any) => {
      const { icon, titleId } = data
      formData.value.icon = icon
      formData.value.titleId = titleId
    }
    // 选择日期
    const onDateConfirm = (value: string) => {
      dateVisible.value = false;
      formData.value.date = dayjs(value).format('YYYY-MM-DD ')+dayjs().format('HH:mm:ss')
      date.value = dayjs(value).format('M月D日') as never
    };
    // 关闭编辑类的组件
    const handleGoReturn = () => {
      editClassVisible.value = false
    }
    // 返回上一页
    const handleGoBook = () => {
      router.push('/bookManage')
    }
    // 点击账本
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const handleClickBook = (item: any) => {
      store.commit('get_book', item)
      localStorage.setItem('book', JSON.stringify(item))
      bookVisible.value = false
    }
    // 通过账单id获取账单详情
    const getBillDetailById = () => {
      getBillDetail({ id: Number(route.query.id) }).then((res) => {
        if(typeof res.code === 'number' && res.code === 100) {
          handleGetEditData(res.data)
        }
      })
    }
    // bookkeepingType为edit时获取data数据
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const handleGetEditData = (billData: any) => {
      const { type, titleId, subTitleId, icon, desc, id }  = billData
      formData.value = {
        type, 
        titleId: subTitleId ? subTitleId : titleId, 
        icon, 
        money: billData.money, 
        date: billData.date, 
        bookId: billData.book.id,
        desc
      }
      money.value = String(billData.money)
      date.value = dayjs(billData.date).format('M月D日') as never
      bookkeepingId.value = id
      defaultDate.value = new Date(billData.date)
      cancelValue.value = '完成'
      let bigIndex = -1
      let smallIndex = -1
      if(type === 'pay') {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const bigClass = payData.value.filter((item: any, index: number) => {
          if(item.id === titleId) {
            bigIndex = index
          }
          return item.id === titleId
        })[0]
        if(subTitleId && bigClass) {
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          bigClass.children.filter((item: any, index: number) => {
            if(item.id === subTitleId) {
              smallIndex = index
            }
            return item.id === subTitleId
          })[0]
        }
        bookGrid.value.handleSelectedBigTypeIndex(bigIndex)
        subTitleId ? bookGrid.value.handleSelectedSmallTypeIndex(smallIndex) : ''
      } else {
        handleSelectedType('income')
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        incomeData.value[0].children.filter((item: any, index: number) => {
          if(item.id === subTitleId) {
            smallIndex = index
          }
          return item.id === subTitleId
        })
        bookGrid.value.handleSelectedSmallTypeIndex(smallIndex)
      }
    }
    const handleGoEditClass = () => {
      router.push('/editClass')
    }
    onMounted(() => {
      date.value = dayjs().format('M月D日') as never
      formData.value.date = dayjs().format('YYYY-MM-DD ')+dayjs().format('HH:mm:ss')
      if(route.query.id && bookkeepingType.value === 'edit') {
        getBillDetailById()
      }
      if(route.query.date) {
        defaultDate.value = new Date(JSON.parse(route.query.date as string))
        date.value = dayjs(defaultDate.value as Date).format('M月D日') as never
      }
    })
    return {
      selectedType,
      payData,
      data,
      inputData,
      money,
      cancelValue,
      editClassVisible,
      date,
      today,
      dateVisible,
      showData,
      formData,
      bookVisible,
      bookData,
      book,
      bookGrid,
      defaultDate,
      handleSelectedType,
      handleClickNumber,
      handleGoBack,
      getSelectedType,
      onDateConfirm,
      handleGoReturn,
      handleGoBook,
      handleClickBook,
      handleGoEditClass
    };
  }
})
</script>

<style scoped>
@import url('../../assets/iconfont/iconfont.css');
  .bookkeeping_header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 0 20px;
  }
  .header_go_back {
    font-size: 20px;
  }
  .header_type {
    display: flex;
    align-items: center;
    color: rgb(133, 133, 133);
  }
  .header_type_item {
    padding: 0 18px;
    width: 50px;
  }
  .header_select_type {
    font-size: 20px;
    color: #eb7775;
    position: relative;
  }
  .header_select_type::before {
    content: "";
    position: absolute;
    width: 38px;
    height: 24px;
    border-radius: 50%;
    background-image: linear-gradient(67deg, #F9C3C2, #fff);
    top: 32%;
    left: 22%;
    z-index: -1;
  }
  .bookkeeping_input {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    z-index: 9;
    background-color: #fff;
    font-weight: 600;
  }
  .input_show {
    display: flex;
    border-top: #e8e8e6 solid 1px;
    border-bottom: #e8e8e6 solid 1px;
    height: 40px;
    line-height: 40px;
    padding: 0 14px;
    text-align: left;
  }
  .input_show .iconfont {
    padding-right: 4px;
  }
  .input_label {
    width: 24%;
  }
  .input_show input {
    border: none;
    width: 60%;
  }
  .input_show input:focus {
    border: none;
    outline: none;
  }
  .input_money {
    font-size: 20px;
    text-align: right;
    width: 20%;
    color: #eb7775;
  }
  .input_info {
    display: flex;
    padding: 0 14px;
    height: 40px;
    line-height: 40px;
    border-bottom: #e8e8e6 solid 1px;
    text-align: left;
  }
  .input_info .iconfont {
    padding-right: 4px;
  }
  .input_date {
    width: 24%;
  }
  .input_book {
    width: 30%;
  }
  .input_account {
    width: 34%;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
  .input_number {
    display: flex;
    flex-wrap: wrap;
  }
  .input_number_item {
    width: calc(25% - 1px);
    height: 50px;
    line-height: 50px;
    border-bottom: #e8e8e6 1px solid;
    border-right: #e8e8e6 1px solid;
  }
  .input_number_item:active {
    background-color: #e8e8e6;
  }
  .input_cancel_item {
    background-color: #e8e8e6;
  }
  .input_finish_item {
    background-color: #F9C3C2;
    color: #fff;
  }
  .input_finish_item:active {
    background-color: #fff;
  }
  .click_book {
    margin: 20px;
  }
  .click_book_header {
    display: flex;
    justify-content: space-between;
  }
  .header_title {
    font-weight: 600;
  }
  .click_book_item {
    margin: 26px 0;
    text-align: left;
  }
  .click_book_item p {
    display: inline-block;
    padding-left: 10px;
  }
</style>